#include "../head.h"

// 客户端：创建套接字 (绑定ip地址和端口 只给服务器发送消息可以不用绑定) 连接服务器 发送数据 关闭套接字

int main()
{
    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    // 2.创建结构体
    struct sockaddr_in client_addr;
    memset(&client_addr, 0, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(8888);
    // client_addr.sin_addr.s_addr = inet_addr("192.168.47.180");
    client_addr.sin_addr.s_addr = inet_addr("8.138.248.21");
    // 绑定ip地址和端口（可不写）
    // 3.连接服务器
    int connect_res = connect(sockfd, (struct sockaddr *)&client_addr, sizeof(client_addr));
    if (connect_res < 0)
    {
        perror("connect error");
        return -1;
    }
    printf("connect success\n");

    while (1)
    {
        char buf[1024] = {0};
        printf("请输入发送内容：");
        scanf("%s", buf);
        // 4.发送数据
        ssize_t send_res = send(sockfd, buf, strlen(buf), 0);
        printf("发送数据：%s\n", buf);
        recv(sockfd, buf, sizeof(buf), 0);
        printf("收到: %s\n", buf);
        if (send_res < 0)
        {
            perror("send error");
            return -1;
        }
        if (strcmp(buf, "exit") == 0)
        {
            break;
        }
    }

    close(sockfd);
    printf("client over...\n");
    return 0;
}